class Solution {
public:
    int maxDistinctElements(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        unordered_map<int, int> num_count;
        for (int num : nums) num_count[num]++;
        int pos = INT_MIN, last = INT_MIN;
        int n = 2 * k + 1;
        int ret = 0;
        for (int num : nums) {
            if (num == last) continue;
            last = num;
            int count = num_count[num];
            if (num - k >= pos) {
                ret += min(count, n);
                pos = min(num - k + count, num - k + n);
            }
            else {
                ret += min(count, num + k - pos + 1);
                pos = min(pos + count, num + k + 1);
            }
        }

        return ret;
    }
};